package com.dailyblue.java.spring.rocketmq.普通消息.消息消费;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class 同步消息的消费 {
    public static void main(String[] args) throws Exception {
        // 创建消费者 Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("zhuoyue02");
        // 指定 NameSrv 地址
        consumer.setNamesrvAddr("192.168.160.88:9876");
        // 订阅主题 Topic 和 Tag
        consumer.subscribe("TopicA", "*");
        // 设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt me : list) {
                    String topic = me.getTopic();
                    String tags = me.getTags();
                    byte[] body = me.getBody();
                    String message = new String(body, StandardCharsets.UTF_8);
                    System.out.println("topic:" + topic + ",tags:" + tags + ",message:" + message);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消费者 Consumer
        consumer.start();
    }
}
